/* eslint-disable */
import { loadModules } from 'esri-loader'
import DomLayerView2DClass from './DomLayerView2D'
class DomLayer {
  async init() {
    const [Layer, Collection] = await loadModules(['esri/layers/Layer', 'esri/core/Collection'])
    const DomLayerView2D = await DomLayerView2DClass.init()
    const clazz = Layer.createSubclass({
      declaredClass: 'DomLayer',
      constructor: function (options = {}) {
        const { id, opacity, title, placement } = options
        this.id = id || new Date().valueOf()
        this.opacity = opacity === undefined ? 1 : opacity
        this.title = title
        this.popupEnabled = false
        this.legendEnabled = false
        this.type = 'dom'
        this.placement = placement || 'center-bottom'
      },
      createLayerView: function (view) {
        this.graphics = new Collection(this.graphics)
        this.graphics.on(
          'change',
          function (param) {
            this.emit('change', param)
          }.bind(this)
        )
        this.view = view
        this.layerView = new DomLayerView2D({
          view: view,
          layer: this,
        })

        return this.layerView
      },

      destroyLayerView: function (param) {
        this.graphics = null
        this.layerView.destroy()
      },

      load: function (param) {
        return this
      },
      reorder(graphic, index) {
        this.graphics.reorder(graphic, index)
      },
      render() {
        this.emit('render')
      },
      updateMany(arr) {
        const removed = this.graphics.filter(
          (v = arr.findIndex((u) => u.attributes.objectId === v.attributes.objectId) > -1)
        )
        this.graphics.removeMany(removed)
        this.graphics.addMany(arr)
      },

      update: function (graphic) {
        const removed = this.graphics.find((v) => v.attributes.objectId === graphic.attributes.objectdId)
        this.graphics.remove(removed)
        this.graphics.add(graphic)
      },

      addMany(arr) {
        this.graphics.addMany(arr)
      },

      add: function (graphic) {
        this.graphics.add(graphic)
      },

      removeMany(arr) {
        this.graphics.removeMany(arr)
      },
      remove(graphic) {
        this.graphics.remove(graphic)
      },

      removeAll() {
        this.graphics.removeAll()
      },
    })
    return clazz
  }
}
export default new DomLayer()
